#ifndef SHARE
#define SHARE
 
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <iostream>
#include <vector>
#include <string>
#include<pcl/io/pcd_io.h>
#include<pcl/point_types.h>
using namespace std;
using PointT = pcl::PointXYZI;
 
namespace ShareMem{
    #define Shm_addrees 1203 //共享内存地址标识
    typedef struct ShareData
    {
        int  flag;
        float past_data[10*2]; //图像数据一维数据，之前用了cv::Mat不行，因为无法在结构体里初始化大小
        float pred_data[10*2];
    }  ShareData_;
 
 class ShareMemory{
    public:
            int shmid = shmget((key_t)Shm_addrees, sizeof(ShareData), 0666|IPC_CREAT);
            void *shm = shmat(shmid, (void*)0, 0);
            ShareData *p_share_data= (ShareData*)shm;
    public:
        ShareMemory(){ 
            p_share_data->flag = 0;
            printf("共享内存地址 ： %p\n", (int *)(shm));
         }
          
        ~ShareMemory() {
            cout<<"析构函数执行"<<endl;
            DestroyShare();
        }   
 
        void DestroyShare(){
            shmdt(shm);
            shmctl(shmid, IPC_RMID, 0);
            cout<<"共享内存已经销毁"<<endl;
        }

        void send_past(float* past){
            if(p_share_data->flag == 0){
                if(past== nullptr)//nullptr是c++11新出现的空指针常量
                {
                    printf("文件不存在\n");
                    return;
                }
                else{
                    for (int i = 0; i< 10; i++){
                        // cout<<"check "<<pc_mat[i]<<endl;
                        p_share_data->past_data[i *2 ] = past[i*2];
                        p_share_data->past_data[i *2 + 1] = past[i*2+1];
                    }     
                    p_share_data->flag = 1;
                }
            }
        }
 
        void get_pred(float (*pred)[2]){ 
            if(p_share_data->flag == 2){
                for(int i = 0; i<10;i++){
                    pred[i][0] = p_share_data->pred_data[i*2];
                    pred[i][1] = p_share_data->pred_data[i*2+1];
                }
                p_share_data->flag = 0;
            }else{
                cout<<"didn't get prediction"<<endl;
                for(int i = 0; i<10;i++){
                    pred[i][0] = 0;
                    pred[i][1] = 0;
                }
            }
        }

        void get_flag(int* flag){
            // cout<<"cpp flag "<<p_share_data->flag<<endl;  //这里有cout的话，导致共享内存的值不一样了
            *flag = p_share_data->flag ;   
        }

     };//类定义结束
 
}//namespace 定义
 
 
//按照C语言格式重新打包-python调用
extern "C" {
    ShareMem::ShareMemory share_men_instance;
    void DestroyShare(){
         share_men_instance.DestroyShare();
    }
 
    void send_past(float*  past){
        share_men_instance.send_past(past);
    }

    void get_pred(float (*pred)[2]){
        share_men_instance.get_pred(pred);
    }

    void get_flag(int* flag){
        share_men_instance.get_flag(flag);
    }
}
 
#endif
